package com.huang.controller;

import com.huang.repository.StudentRepository;
import com.huang.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/students")
public class StudentController {
    @Autowired
    private StudentRepository studentRepository;

    @Modifying
    @RequestMapping("/getAllStudents")
    public Object getAllStudents() {
        return studentRepository.findAll();
    }

    @Modifying
    @RequestMapping("/insertStudent")
    public Object insertStudent(@RequestBody Student student) {
        studentRepository.save(student);
        return "success";
    }



    @Modifying
    @RequestMapping("/updateStudent")
    public Object updateStudent(@RequestBody Student student)
    {
        Student oldStudent = studentRepository.findStudentByStudentNum(student.getStudentNum());
        if (oldStudent != null)
        {
            oldStudent.setStudentName(student.getStudentName());
            oldStudent.setSex(student.getSex());
            oldStudent.setClassNum(student.getClassNum());
            studentRepository.save(oldStudent);
        }
        return "success";
    }

    @Modifying
    @RequestMapping("/deleteStudent")
    public String deleteStudent(@RequestParam(value = "studentNum") String studentNum)
    {
        studentRepository.delete(studentNum);
        return "success";
    }


}

